package cn.jsu.oj.dispatchServer.satellite.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 线程工具
 *
 * @author shan
 * @date 2022/07/05
 */
public class ThreadUtil {

    /**
     * 捕获线程
     *
     * @param name 线程名
     * @return {@link Thread }
     */
    public static Thread captureThread(String name) {
        for (Thread thread : Thread.getAllStackTraces().keySet()) {
            if (thread.getName().equals(name)) {
                return thread;
            }
        }
        return null;
    }

    /**
     * 获得所有线程
     *
     * @return {@link List }<{@link Thread }>
     */
    public static List<Thread> getAllThread() {
        return new ArrayList<>(Thread.getAllStackTraces().keySet());
    }

    /**
     * 正常关闭线程池
     *
     * @param executorService 执行线程池
     * @return {@link Boolean }
     */
    public static Boolean closeThreadPool(ExecutorService executorService) {
        executorService.shutdown();
        while (true) {
            try {
                if (executorService.awaitTermination(1, TimeUnit.SECONDS)) {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 立刻关闭线程池
     *
     * @param executorService 执行线程池
     * @return {@link List }<{@link Runnable }>
     */
    public static List<Runnable> closeThreadPoolNow(ExecutorService executorService) {
        List<Runnable> dropList = executorService.shutdownNow();
        while (true) {
            try {
                if (executorService.awaitTermination(1, TimeUnit.SECONDS)) {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            }
        }
        return dropList;
    }
}
